﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebSOAPUI.Lib;
using WebSOAPUI.Lib.Model;

namespace WebSOAPUI
{
    public partial class Ajax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.HandleAJAXRequest();
        }

        #region common

        /// <summary>
        /// 格式化xml
        /// </summary>
        protected void FormatXml()
        {
            var xml = Request.Form["xml"].Trim();
            try
            {
                var fxml = XmlUtils.FormatXml(xml);
                this.ResponseJSON(new { success = true, xml = fxml.ToString() });
            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        /// <summary>
        /// 发送SOAP请求
        /// </summary>
        protected void PostSOAPRequest()
        {
            //"urn:sap-com:document:sap:soap:functions:mc-style"
            //"urn:sap-com:document:sap:soap:functions:mc-style:
            var xml = Request.Form["xml"].Trim();
            var wsID = Request.QueryString["wsID"].ToInt();
            var mID = Request.QueryString["mID"].ToInt();
            var endPoint = string.Empty;
            var soapAction = string.Empty;
            using (var dbContext = new CNOOCDbContext())
            {
                var wsObj = (from ws in dbContext.WebServices
                             where ws.ID == wsID
                             select ws).FirstOrDefault();
                if (wsObj != null)
                {
                    endPoint = wsObj.BindingAddress;
                }

                var mObj = (from m in dbContext.WebServiceMethods
                            where m.ID == mID
                            select m).FirstOrDefault();
                if (mObj != null)
                {
                    soapAction = mObj.SOAPAction;
                }
            }

            //var soapRequest = new SOAPRequest()
            //{
            //    EndPoint = "http://10.63.0.20:8000/sap/bc/srt/rfc/sap/zesapws_mm001/310/zesapws_mm001/zesapws_mm001",
            //    Username = "hh_zhaowei",
            //    Password = "zhaowei8",
            //    SOAPAction = "\"urn:sap-com:document:sap:soap:functions:mc-style:ZESAPWS_MM001:ZesapfunMm001\"",
            //    SOAPData = xml
            //};
            var soapRequest = new SOAPRequest()
            {
                EndPoint = endPoint,
                Username = "hh_zhaowei",
                Password = "zhaowei8",
                SOAPAction = "\"" + soapAction + "\"",
                SOAPData = xml
            };
            soapRequest.Username = ConfigurationManager.AppSettings["wsUsername"];
            soapRequest.Password = ConfigurationManager.AppSettings["wsPassword"];
            try
            {
                var ret = WebServiceUtils.PostSOAPRequest(soapRequest);
                ret = XmlUtils.FormatXml(ret);
                this.ResponseJSON(new { success = true, xml = ret });
            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        /// <summary>
        /// 解析wsdl内容
        /// </summary>
        protected void ResolveWsdl()
        {
            var xml = Request.Form["xml"].Trim();
            try
            {
                var wsInfo = WebServiceUtils.ResolveServiceInfo(xml);
                this.ResponseJSON(new { success = true, wsInfo = wsInfo });
            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        #endregion

        #region dao

        protected void SaveWsdlInfo()
        {
            var json = Request.Form["info"];
            WebServiceInfo wsInfo = null;
            try
            {
                wsInfo = JsonConvert.DeserializeObject<WebServiceInfo>(json);
                using (var dbContext = new CNOOCDbContext())
                {
                    var wsEntity = new WebServiceEntity();
                    wsEntity.CreatedOn = DateTime.Now;
                    wsEntity.DeleteFlag = false;
                    wsEntity.ServiceDesc = wsInfo.Description;
                    wsEntity.ServiceName = wsInfo.Service;
                    wsEntity.Sort = 0;
                    wsEntity.UpdatedOn = DateTime.Now;
                    wsEntity.BindingAddress = wsInfo.SOAPAddress;
                    wsEntity.WSDLAddress = wsInfo.WSDLUrl;
                    wsEntity.WsNameSapce = wsInfo.Namespace;
                    dbContext.WebServices.Add(wsEntity);

                    if (wsInfo.Methods != null && wsInfo.Methods.Count > 0)
                    {
                        foreach (var m in wsInfo.Methods)
                        {
                            var mEntity = new WebServiceMethodEntity();
                            mEntity.CreatedOn = DateTime.Now;
                            mEntity.DeleteFlag = false;
                            mEntity.Sort = 0;
                            mEntity.WebServiceEntityID = wsEntity.ID;
                            mEntity.SOAPAction = m.SOAPAction;
                            mEntity.MethodName = m.MethodName;
                            dbContext.WebServiceMethods.Add(mEntity);
                        }
                    }
                    dbContext.SaveChanges();
                }
                this.ResponseJSON(new { success = true });
            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        protected void LoadWebServices()
        {
            using (var dbContext = new CNOOCDbContext())
            {
                var q = from ws in dbContext.WebServices
                        where !ws.DeleteFlag
                        orderby ws.Sort ascending
                        select ws;

                this.ResponseJSON(q.ToList());
            }
        }

        protected void LoadWebServiceMethods()
        {
            var wsID = Request.QueryString["id"].ToInt();
            using (var dbContext = new CNOOCDbContext())
            {
                var q = from wm in dbContext.WebServiceMethods
                        where !wm.DeleteFlag && wm.WebServiceEntityID == wsID
                        orderby wm.Sort ascending
                        select wm;

                this.ResponseJSON(q.ToList());
            }
        }

        protected void LoadWebServiceMethodDataPakcs()
        {
            var wmID = Request.QueryString["id"].ToInt();
            using (var dbContext = new CNOOCDbContext())
            {
                var q = from wm in dbContext.SOAPRequestDataPackes
                        where !wm.DeleteFlag && wm.WebServiceMethodID == wmID
                        orderby wm.Sort ascending
                        select wm;

                this.ResponseJSON(q.ToList());
            }
        }

        protected void SaveWebServiceMethodDataPakcs()
        {
            var json = Request.Form["json"];
            try
            {
                var list = JsonConvert.DeserializeObject<List<WebServiceSOAPRequestDataPackEntity>>(json);
                using (var dbContext = new CNOOCDbContext())
                {
                    foreach (var item in list)
                    {
                        if (item.ID == 0)
                        {
                            item.CreatedOn = DateTime.Now;
                            dbContext.SOAPRequestDataPackes.Add(item);
                        } else
                        {
                            dbContext.Entry<WebServiceSOAPRequestDataPackEntity>(item).State = System.Data.Entity.EntityState.Modified;
                        }
                    }
                    dbContext.SaveChanges();
                }
                this.ResponseJSON(new { success = true });

            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        protected void DeleteDataPack()
        {
            try
            {
                var id = Request.QueryString["id"].ToInt();
                using (var dbContext = new CNOOCDbContext())
                {
                    var q = from dp in dbContext.SOAPRequestDataPackes
                            where dp.ID == id
                            select dp;

                    var obj = q.FirstOrDefault();
                    if (obj != null)
                    {
                        dbContext.SOAPRequestDataPackes.Remove(obj);
                        dbContext.SaveChanges();
                    }
                }
                this.ResponseJSON(new { success = true });
            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        protected void DeleteWebServices()
        {
            var id = Request.QueryString["id"].ToInt();
            using (var dbContext = new CNOOCDbContext())
            {
                var wsEntity = dbContext.WebServices.FirstOrDefault(it => it.ID == id);
                if (wsEntity != null)
                {
                    //wsEntity.DeleteFlag = true;
                    dbContext.WebServices.Remove(wsEntity);
                    var q = from wm in dbContext.WebServiceMethods
                            where wm.WebServiceEntityID == wsEntity.ID
                            select wm;
                    var wss = q.ToList();
                    var ids = wss.Select(it => it.ID.ToString());
                    dbContext.WebServiceMethods.RemoveRange(wss);

                    if (ids.Count() > 0)
                    {
                        var sql = "DELETE FROM T_MGT_WebServiceSOAPRequestDataPack WHERE WebServiceMethodID IN";
                        var strs = ids.Aggregate((i1, i2) => i1.ToString() + "," + i2.ToString());
                        sql += "(" + strs + ")";
                        dbContext.Database.ExecuteSqlCommand(sql);
                    }
                    dbContext.SaveChanges();
                }
            }
        }

        protected void UpdateWebServicesSort()
        {
            var id = Request.QueryString["id"].ToInt();
            using (var dbContext = new CNOOCDbContext())
            {
                var wsEntity = dbContext.WebServices.FirstOrDefault(it => it.ID == id);
                if (wsEntity != null)
                {
                    wsEntity.Sort = Request.QueryString["sort"].ToInt();
                    dbContext.SaveChanges();
                }
            }
        }

        protected void UpdateMethodSort()
        {
            var id = Request.QueryString["id"].ToInt();
            using (var dbContext = new CNOOCDbContext())
            {
                var mEntity = dbContext.WebServiceMethods.Where(it => it.ID == id).FirstOrDefault();
                if (mEntity != null)
                {
                    mEntity.Sort = Request.QueryString["sort"].ToInt();
                    dbContext.SaveChanges();
                }
            }
        }

        protected void UpdateWebService()
        {
            var json = Request.Form["json"];
            try
            {
                var wsEntity = JsonConvert.DeserializeObject<WebServiceEntity>(json);
                using (var dbContext = new CNOOCDbContext())
                {
                    var wsObj = dbContext.WebServices.Find(wsEntity.ID);
                    if (wsObj != null)
                    {
                        wsObj.ServiceDesc = wsEntity.ServiceDesc;
                        wsObj.WSDLAddress = wsEntity.WSDLAddress;
                        wsObj.BindingAddress = wsEntity.BindingAddress;
                        wsObj.UpdatedOn = DateTime.Now;
                        dbContext.SaveChanges();
                    }
                }
                this.ResponseJSON(new { success = true });
            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        #region attachment
        protected void LoadWebServiceAttachments()
        {
            var wsID = Request.QueryString["wsID"].ToInt();
            using (var dbContext = new CNOOCDbContext())
            {
                var q = from a in dbContext.WebServiceAttachments
                        where a.WebServiceEntityID == wsID
                        select new { FileName = a.FileName, ID = a.ID,CreatedOn = a.CreatedOn };

                this.ResponseJSON(q);
            }
        }

        protected void DeleteWebServiceAttachment()
        {
            var attaID = Request.QueryString["attaID"].ToInt();
            try
            {
                using (var dbContext = new CNOOCDbContext())
                {
                    var attaObj = dbContext.WebServiceAttachments.Find(attaID);
                    if (attaObj != null)
                    {
                        dbContext.WebServiceAttachments.Remove(attaObj);
                        dbContext.SaveChanges();
                    }
                }
                this.ResponseJSON(new { success = true });
            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }

        protected void UpdateAttachmentCreatedOn()
        {
            var json = Request.Form["json"];
            try
            {
                WebServiceAttachment atta = JsonConvert.DeserializeObject<WebServiceAttachment>(json);
                using (var dbContext = new CNOOCDbContext())
                {
                    var obj = dbContext.WebServiceAttachments.Find(atta.ID);
                    obj.CreatedOn = atta.CreatedOn;
                    dbContext.SaveChanges();
                }
                this.ResponseJSON(new { success = true });

            } catch (Exception ex)
            {
                this.ResponseJSON(new { success = false, error = ex.Message });
            }
        }
        #endregion

        #endregion

        #region login
        protected void DoLogin()
        {
            var username = Request.Form["username"].GetSafeString();
            var password = Request.Form["password"].GetSafeString();

            var sysUsername = ConfigurationManager.AppSettings["sysUsername"];
            var sysPassword = ConfigurationManager.AppSettings["sysPassword"];
            var success = false;
            if (username.EqualsIgnoreCase(sysUsername) && password.EqualsIgnoreCase(sysPassword))
            {
                success = true;
                //Session["Login"] = success;
                System.Web.Security.FormsAuthentication.SetAuthCookie(username, true);
            }
            this.ResponseJSON(new { success = success });
        }

        protected void CheckLogin()
        {
            if (Request.IsAuthenticated)
            {
                this.ResponseJSON(new { success = true });
            } else
            {
                this.ResponseJSON(new { success = false });
            }
        }

        protected void DoLogout()
        {
            FormsAuthentication.SignOut();
            //Session["Login"] = null;
        }
        #endregion
    }
}